from django.shortcuts import render
import json,random,string,datetime,time,calendar,urllib,hashlib
from django.http import HttpResponse
from django.core.serializers import serialize
from django.views.decorators.csrf import csrf_exempt
from wxhoutai.unit import butesTotoJson
from django.core.cache import cache
from django.views.decorators.cache import cache_page

appid = "自己的appid"
secret = "自己的secret"

#获取微信token
@cache_page(7000)
def wxToken(request):   
    tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+""
    token = urllib.request.urlopen(tokenUrl).read()
    token = json.loads(token.decode('utf-8'))
    return HttpResponse(json.dumps(token))

#获取ticket
@csrf_exempt
def wxTicket(request):
    url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+request.POST.get("access_token")+"&type=jsapi"
    data = urllib.request.urlopen(url).read()
    data = json.loads(data.decode('utf-8'))
    noncestr = ''.join(random.sample(string.ascii_letters + string.digits, 8))
    jsapi_ticket = data['ticket']
    timestamp = str(calendar.timegm(time.gmtime()))
    url = request.POST.get("url")
    sigStr = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url+""
    sigSh1 = hashlib.sha1(sigStr.encode('utf-8')).hexdigest()
    ticketData = {
        'signature' : sigSh1,
        'noncestr' : noncestr,
        'jsapi_ticket' : data['ticket'],
        'timestamp' : calendar.timegm(time.gmtime()),
    }
    return HttpResponse(json.dumps(ticketData))

#获取登陆用户信息
@cache_page(7000)
def getUserInfo(request):
    #通过code换取网页授权access_token
    url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx08b045c7276eb2cd&secret=a0e5f20568ada0ad0d4a8e834758acdd&code="+request.GET.get('code')+"&grant_type=authorization_code"
    token = urllib.request.urlopen(url).read()
    token = json.loads(token.decode('utf-8'))

    userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token['access_token']+"&openid="+token['openid']+"&lang=zh_CN"
    userInfo = urllib.request.urlopen(userUrl).read()
    userInfo = json.loads(userInfo.decode('utf-8'))
    return HttpResponse(json.dumps(userInfo))
